package ext.tianma.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import wt.method.RemoteAccess;
import wt.method.RemoteMethodServer;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTPrincipal;
import wt.org.WTUser;
import wt.util.WTException;
import wt.util.WTProperties;

/**
 * 导出系统中的组和用户到csv文件
 * <BR>用户：Users.csv
 * <BR>组：Groups.csv
 * <BR>组和组：Group2Group.csv
 * <BR>组和用户：Group2Users.csv
 * 
 * @author zhangjianwen
 * @since 2017-06-20
 */
public class ExportGroupUser implements RemoteAccess, Serializable {

	//需要排除的系统默认组：按需添加
	private static final List EXCLUDE_GROUPS_LIST = Arrays.asList(new String[] {
			"Administrators",
			"Attribute Administrators",
			"Gateway Administrator",
			"Gateway Default Application",
			"Gateway Publisher",
			"LifeCycleAdministrators",
			"Replication Managers", 
			"Type Administrators",
			"WorkflowAdministrators",
			"WorkflowAuthors", 
			"Unrestricted Organizations", 
			"Demo Organization",
			"All Supplier Administrators",
			"Unrestricted Supplier Administrators", 
			});

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static HashMap<String, WTUser> userMap = new HashMap<String, WTUser>();
	private static HashMap<String, Set<String>> groupuserMap = new HashMap<String, Set<String>>();
	private static Set<String> groupSet = new HashSet<String>();
	private static Set<String> group2groupList = new HashSet<String>();
	public static String codebaseLocation = "";
	
	static {
		try {
			WTProperties properties = WTProperties.getLocalProperties();
			codebaseLocation = properties.getProperty("wt.codebase.location");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	// java ext.xbc.user.ExportGroupUserUtil
	public static void main(String[] args) {
		try {
			RemoteMethodServer rms = RemoteMethodServer.getDefault();
			rms.setUserName("wcadmin");
			rms.setPassword("tmadmin");
			String exportFolder = codebaseLocation+File.separator+"temp";
			Class[] acls = { String.class };
			Object[] aobj = { exportFolder };
			System.out.println("------------------Begin to export Group user to -----------------"+ exportFolder);
			rms.invoke("exportGroupUsers",ExportGroupUser.class.getName(), null, acls, aobj);
			System.out.println("------------------End to export Group user to -----------------"+ exportFolder);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void parseGroup(WTGroup group) throws WTException {
		if (EXCLUDE_GROUPS_LIST.indexOf(group.getName()) >= 0)
			return;
		String groupName = group.getName();
		groupSet.add( groupName );

		Enumeration ee = OrganizationServicesHelper.manager.members(group, false);
		if(ee != null){
			Set<String> userSet = null;
			if(groupuserMap.containsKey(groupName)){
				userSet = groupuserMap.get(groupName);
			}else{
				userSet = new HashSet<String>();
			}
			while (ee.hasMoreElements()) {
				
				
				WTPrincipal principal = (WTPrincipal) ee.nextElement();
				if (principal instanceof WTUser) {
					WTUser user = (WTUser) principal;
					String userName = user.getName();
					if (!userMap.containsKey(userName)) {
						userMap.put(userName, user);
					}
					userSet.add(userName);
				}
				if(principal instanceof WTGroup) {
					WTGroup childGroup = (WTGroup) principal;
					parseGroup(childGroup);
					String group2key = groupName + "," + childGroup.getName();
					group2groupList.add(group2key);
				}else{
				}
			}
			groupuserMap.put(groupName, userSet);
		}
	}

	public static void exportGroupUsers(String exportFolder) throws Exception {
		if (!RemoteMethodServer.ServerFlag) {
			RemoteMethodServer.getDefault()
					.invoke("exportGroupUsers",
							ExportGroupUser.class.getName(), null,
							new Class[] { String.class },
							new Object[] { exportFolder });
		}
		String userCSV = exportFolder + File.separator + "Users.csv";
		String groupCSV = exportFolder + File.separator + "Groups.csv";
		String groupuserCSV = exportFolder + File.separator + "Group2Users.csv";
		String group2groupCSV = exportFolder + File.separator + "Group2Group.csv";

		FileOutputStream useroutputstream = new FileOutputStream(userCSV, true);
		FileOutputStream groupoutputstream = new FileOutputStream(groupCSV,true);
		FileOutputStream groupuseroutputstream = new FileOutputStream(groupuserCSV, true);
		FileOutputStream group2groupoutputstream = new FileOutputStream(group2groupCSV, true);

		PrintWriter usercsvWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(useroutputstream)));
		PrintWriter groupcsvWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(groupoutputstream)));
		PrintWriter groupusercsvWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(groupuseroutputstream)));
		PrintWriter group2groupcsvWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(group2groupoutputstream)));
		
		Enumeration en = OrganizationServicesHelper.manager.allGroups();

		while (en != null && en.hasMoreElements()) {
			Object obj = en.nextElement();
			if (obj instanceof WTGroup) {
				WTGroup group = (WTGroup) obj;
				if (EXCLUDE_GROUPS_LIST.indexOf(group.getName()) >= 0)
					continue;
				parseGroup(group);
			}
		}
		writeUserCSV(usercsvWriter);
		writeGroupCSV(groupcsvWriter);
		writeGroupUserCSV(groupusercsvWriter);
		writeGroup2GroupCSV(group2groupcsvWriter);
		
	}

	public static void writeUserCSV(PrintWriter usercsvWriter) throws WTException{
		String line1 = "工号,登录名称,姓,名,组,手机号,邮箱,区域,工作场地,入职日期";
		usercsvWriter.println(line1);
		Iterator<String> userIter = userMap.keySet().iterator();
		while(userIter.hasNext()){
			String userName = userIter.next();
			WTUser user = userMap.get(userName);
			String alternateUserName = getAlternateName(user,"alternateUserName1");//获取用户替代名
			String fullName = user.getFullName();
			Enumeration groupNames = user.parentGroupNames();//获得用户所在的组
			String groupName ="";
			String groupName1 ="";
			while(groupNames.hasMoreElements()){
				groupName1 = (String)groupNames.nextElement();
				if(groupName1.contains("离职")) {
					groupName ="离职";
				}
			}
			if(fullName.contains("(")) {
				fullName = fullName.substring(0, fullName.indexOf("("));//去掉()里的数据
			}
			fullName = fullName.replace(" ", "");//去掉空格
			String reg = "[^\u4e00-\u9fa5]";
			String nameHZ = fullName.replaceAll(reg, "");//拿到汉字姓名
			String namePY = fullName.replace(nameHZ, "");//拿到姓名全拼
			namePY = namePY.toLowerCase();//将字母改为全小写
			String email = user.getEMail() == null? "":user.getEMail();
			String line = alternateUserName +","+ alternateUserName +","+ nameHZ +","+ namePY +","+ groupName + ",," + email+ ",,,,," ;
			usercsvWriter.println(line);
		}
		usercsvWriter.flush();
		usercsvWriter.close();
	}
	
	
	public static void writeGroupCSV(PrintWriter groupcsvWriter) throws WTException{
		String line1 = "#Group,user,用户组名称";
		String line2 = "#Group,user,groupName";
		groupcsvWriter.println(line1);
		groupcsvWriter.println(line2);
		
		Iterator<String> groupIter = groupSet.iterator();
		while(groupIter.hasNext()){
			String groupName = groupIter.next();
			groupcsvWriter.println("Group,," + groupName);
		}
		groupcsvWriter.flush();
		groupcsvWriter.close();
	}
	
	public static void writeGroup2GroupCSV(PrintWriter groupcsvWriter) throws WTException{
		String line1 = "#GroupGroup,创建者,*父项组,*子项组,Directory Service";
		String line2 = "#GroupGroup,user,parentGroupName,childGroupName";
		groupcsvWriter.println(line1);
		groupcsvWriter.println(line2);
		Iterator<String> group2GropuSet = group2groupList.iterator();
		while(group2GropuSet.hasNext()){
			groupcsvWriter.println("GroupGroup,," + group2GropuSet.next());
		}
		groupcsvWriter.flush();
		groupcsvWriter.close();
	}
	
	public static void writeGroupUserCSV(PrintWriter groupusercsvWriter) throws WTException{
		String line1 = "#UserGroup,user,*组名,csvgroupNameDirectoryService,*用户名,csvuserNameDirectoryService,csvDirectoryService";
		String line2 = "#UserGroup,user,*组名,csvgroupNameDirectoryService,*用户名,csvuserNameDirectoryService,csvDirectoryService";
		groupusercsvWriter.println(line1);
		groupusercsvWriter.println(line2);
		
		Iterator<String> groupuserIter = groupuserMap.keySet().iterator();
		while(groupuserIter.hasNext()){
			String groupName = groupuserIter.next();
			Set<String> userSet = groupuserMap.get(groupName);
			for(String userName : userSet){
				String line = "UserGroup,," + groupName + ",," + userName + ",,";
				groupusercsvWriter.println(line);
			}
		}
		groupusercsvWriter.flush();
		groupusercsvWriter.close();
	}
	/**
	 * 获得用户替代名
	 * @param paramWTUser
	 * @param paramString
	 * @return
	 * @throws WTException
	 */
	public static String getAlternateName(WTUser paramWTUser, String paramString) throws WTException {
	    String str = null;
	    Enumeration localEnumeration = paramWTUser.getAttributes().getValues("uid");

	    ArrayList localArrayList = Collections.list(localEnumeration);
	    localArrayList.remove(paramWTUser.getName());
	    if ((paramString.equals("alternateUserName1")) && (localArrayList.size() > 0))
	      str = (String)localArrayList.get(0);
	    else if ((paramString.equals("alternateUserName2")) && (localArrayList.size() > 1))
	      str = (String)localArrayList.get(1);
	    else if ((paramString.equals("alternateUserName3")) && (localArrayList.size() > 2))
	      str = (String)localArrayList.get(2);
	    else if ((paramString.equals("alternateUserName4")) && (localArrayList.size() > 3)) {
	      str = (String)localArrayList.get(3);
	    }
	    return str;
	  }
}
